from pathlib import Path
import os
from requests import get
import zipfile
import subprocess
import sys

# port = int(sys.argv[1])
# rl_port = int(sys.argv[2])
# port = 10001

target_ports = []
n = len(sys.argv)
for i in range(1, n):
    target_ports.append(int(sys.argv[i]))

def init():
    p_str = "C:\\users\\netease\\frp"
    path = Path(p_str)
    path.mkdir(parents=True, exist_ok=True)

    # Get the current working directory
    cwd = os.getcwd()

    # Print the current working directory
    print("Current working directory: {0}".format(cwd))

    # Change the current working directory
    os.chdir(p_str)

    # Print the current working directory
    print("Current working directory: {0}".format(os.getcwd()))

    frp_file_url = "https://gitlab.com/wsszh/file-server/-/raw/main/frp_0.38.0_windows_test.zip?inline=false"
    frp_path = "frp_0.38.0_windows_test"
    frp_file = frp_path + ".zip"

    # download frp
    with open(frp_file, "wb") as file:
        resp = get(frp_file_url)
        file.write(resp.content)

    # unzip
    with zipfile.ZipFile(frp_file, "r") as zip_ref:
        zip_ref.extractall(".")

    os.chdir(frp_path)

    in_file = r'frpc-RL.ini'
    for i in range(len(target_ports)):
        replace_in_file(in_file, in_file, "TARGET-PORT{i}".format(i=i), str(target_ports[i]))

    # replace_in_file(in_file, in_file, "[RDP]", "[RPD-{port}]".format(port=port))
    # replace_in_file(in_file, in_file, "RDP-PORT", str(port))
    # replace_in_file(in_file, in_file, "[RL]", "[RL-{port}]".format(port=rl_port))
    # replace_in_file(in_file, in_file, "RL-PORT", str(rl_port))

    subprocess.Popen(["frpc.exe", "-c", in_file])
    subprocess.Popen(["start", "powershell"], shell = True)    

def rl():
    p_str = "E:\\"
    path = Path(p_str)
    path.mkdir(parents=True, exist_ok=True)
    os.chdir(p_str)
    
    train_script_url = "https://gitlab.com/wsszh/file-server/-/raw/main/rl/train_script.zip?inline=false"
    train_script_path = "D90"
    train_script_file = train_script_path + ".zip"

    # download
    with open(train_script_file, "wb") as file:
        resp = get(train_script_url)
        file.write(resp.content)

    # unzip
    with zipfile.ZipFile(train_script_file, "r") as zip_ref:
        zip_ref.extractall(".")

    os.chdir(train_script_path)
    subprocess.Popen(["python", "d90_train_server.py"])

    subprocess.Popen(["C:\Python38\python.exe", "-m", "pip", "install", "msgpack", "msgpack_numpy", "zmq"])

    rlsdk_server_path = p_str + train_script_path + "\\" + "rlsdk_server"
    path = Path(rlsdk_server_path)
    path.mkdir(parents=True, exist_ok=True)
    os.chdir(rlsdk_server_path)
    
    rlsdk_server_url = "https://gitlab.com/wsszh/file-server/-/raw/main/rl/rlsdk_server.zip?inline=false"
    rlsdk_server_file = "rlsdk_server.zip"

    # download
    with open(rlsdk_server_file, "wb") as file:
        resp = get(rlsdk_server_url)
        file.write(resp.content)

    # unzip
    with zipfile.ZipFile(rlsdk_server_file, "r") as zip_ref:
        zip_ref.extractall(".")


def replace_in_file(in_file, out_file, search_text, replace_text):
    # Opening our text file in read only
    # mode using the open() function
    with open(in_file, 'r') as file:

        # Reading the content of the file
        # using the read() function and storing
        # them in a new variable
        data = file.read()

        # Searching and replacing the text
        # using the replace() function
        data = data.replace(search_text, replace_text)

    # Opening our text file in write only
    # mode to write the replaced content
    with open(out_file, 'w') as file:

        # Writing the replaced data in our
        # text file
        file.write(data)

if __name__ == "__main__":
    init()
    rl()
    # os.system("taskmgr")    